extends Enemy
# -------------------------变量声明-----------------------------#
enum State{
	IDLE,
	WALK,
	RUN,
	HURT,
	DIE,
}
# 攻击力
const ATTACK:=1 

# 击退距离
const KNOCKBACK_AMOUNT:=510
# 受到伤害
var pending_damage:Damage

# 墙面检测
@onready var wallCheck=$Graphics/WallCheck
# 地面检测
@onready var floorCheck=$Graphics/FloorCheck
# 玩家检测
@onready var playerCheck=$Graphics/PlayerCheck
# 仇恨计时器
@onready var calmDownTimer=$CalmDownTimer

# -------------------------生命周期-----------------------------#
# 状态流转
func getNextState(state:State) -> int:
	if !stats.health:
		return State.DIE if state!=State.DIE else stateMachine.KEEP_CURRENT
	if pending_damage:
		return State.HURT

	match state:
		# 闲置2秒后移动
		State.IDLE:
			if seePlayer():
				return State.RUN
			if stateMachine.stateTime>2:
				return State.WALK
		# 碰墙或空地回头
		State.WALK:
			if seePlayer():
				return State.RUN
			if wallCheck.is_colliding() or not floorCheck.is_colliding():
				return State.IDLE
		# 退出攻击状态 
		State.RUN:
			if calmDownTimer.is_stopped():
				return State.WALK
		State.HURT:
			if not animationPlayer.is_playing():
				return State.RUN
	return StateMachine.KEEP_CURRENT
# 帧流动
func tickPhysics(state:State,delta:float)-> void:
	match state:
		State.IDLE,State.HURT,State.DIE:
			move(0.0,delta)
		State.WALK:
			move(maxSpeed/3,delta)
		State.RUN:
			if wallCheck.is_colliding() or not floorCheck.is_colliding():
				direction*=-1
			move(maxSpeed,delta)
			if seePlayer():
				calmDownTimer.start()
	pass

# -------------------------函数调用-----------------------------#
# 根据状态 变更动画及后续操作
func transitionState(_from:State,to:State)->void:
	# print("[%s] %s => %s" % [
	# 	Engine.get_physics_frames(),
	# 	State.keys()[from] if from!=-1 else 'start',
	# 	State.keys()[to]
	# ])
	match to:
		State.IDLE:
			animationPlayer.play('idle')
			if wallCheck.is_colliding():
				direction *= -1
		State.WALK:
			animationPlayer.play('walk')
			if not floorCheck.is_colliding():
				direction *= -1
		State.RUN:
			animationPlayer.play('run')
		State.HURT:
			animationPlayer.play('hurt')
			stats.health-=pending_damage.amount
			var dir:=pending_damage.source.global_position.direction_to(global_position)
			velocity=dir*KNOCKBACK_AMOUNT

			# 野猪受攻击后面向玩家
			if  dir.x>0:
				direction=Direction.LEFT
			else:
				direction=Direction.RIGHT

			pending_damage=null

		State.DIE:
			animationPlayer.play('die')
	pass

# 看见玩家
func seePlayer():
	if not playerCheck.is_colliding():
		return false
	return playerCheck.get_collider() is Player

# 计算攻击力伤害
func damage():
	return ATTACK

# 受到攻击的信号
func _on_hurt_box_hurt(hitBox:HitBox) -> void:
	pending_damage=Damage.new()
	pending_damage.amount=hitBox.owner.damage()
	pending_damage.source=hitBox.owner

